package com.ghsc.ghxc.jsb.ui.live.view

import android.content.Context
import android.text.TextUtils
import android.util.Log
import com.alivc.auicommon.common.base.callback.UICallback
import com.alivc.auicommon.common.base.error.Errors
import com.alivc.auicommon.common.base.exposable.Callback
import com.alivc.auicommon.common.base.util.CommonUtil
import com.alivc.auicommon.common.roombase.Const
import com.alivc.auimessage.AUIMessageConfig
import com.alivc.auimessage.MessageServiceFactory
import com.alivc.auimessage.listener.InteractionCallback
import com.alivc.auimessage.model.base.AUIMessageUserInfo
import com.alivc.auimessage.model.base.InteractionError
import com.aliyun.aliinteraction.uikit.uibase.helper.IMLoginHelper
import com.aliyun.aliinteraction.uikit.uibase.util.AppUtil
import com.aliyun.auiappserver.AppServerApi
import com.aliyun.auiappserver.AppServerTokenManager
import com.aliyun.auiappserver.model.CreateLiveRequest
import com.aliyun.auiappserver.model.GetLiveRequest
import com.aliyun.auiappserver.model.LiveModel
import com.aliyun.auiappserver.model.UpdateLiveRequest
import com.aliyun.auipusher.LiveParam
import com.aliyun.auipusher.LiveRole
import com.aliyun.auipusher.config.AliLiveMediaStreamOptions
import com.cn.appcore.event.RxBus
import com.cn.appcore.event.RxBusBean
import com.cn.appcore.ext.loge
import com.cn.appcore.ext.showToast
import com.cn.appcore.utils.GsonUtil
import com.ghsc.ghxc.jsb.config.CustSignKey
import com.ghsc.ghxc.jsb.config.UserManager
import org.json.JSONException
import org.json.JSONObject
import java.io.Serializable

/**
 * @author puke
 * @version 2021/7/20
 */
class CustLiveProtoType private constructor() : Serializable {
    fun setup(context: Context, param: OpenLiveParam?, callback: Callback<String>?) {
        val uiCallback = UICallback(callback)
        if (AppUtil.isNetworkInvalid(context)) {
            uiCallback.onError("当前网络不可用，请检查后再试")
            return
        }
        if (param == null) {
            uiCallback.onError("param不能为空")
            return
        }
        if (param.role == null) {
            uiCallback.onError("role不能传空")
            return
        }
        if (TextUtils.isEmpty(param.nick)) {
            uiCallback.onError("nick参数不能为空")
            return
        }
        val userInfo = AUIMessageUserInfo()
        userInfo.userId = Const.getUserId()
        userInfo.userNick = UserManager.getUserName()
        userInfo.userAvatar=UserManager.getUserHead()
        loge("AUIMessageUserInfo="+userInfo.userId+"name="+userInfo.userNick)
        fetchMessageToken(userInfo, object : InteractionCallback<Void?> {
            override fun onSuccess(data: Void?) {
                IMLoginHelper.login(userInfo, object : InteractionCallback<Void?> {
                    override fun onSuccess(unused: Void?) {
                        val role = param.role
                        val liveId = param.liveId
                        val hasLive = !TextUtils.isEmpty(liveId)
                        if (role == LiveRole.ANCHOR) {
                            // 主播身份
                            if (hasLive) {
                                // 有直播, 直接进入直播间
                                openLiveRoom(context, null, param, uiCallback)
                            } else {
                                // 无直播, 先创建再进入
                                createAndOpenLiveRoom(context, param, uiCallback)
                            }
                        } else {
                            // 观众身份
                            if (hasLive) {
                                // 有直播, 直接进入直播间
                                openLiveRoom(context, null, param, uiCallback)
                            } else {
                                // 无直播, 报错
                                uiCallback.onError(Errors.PARAM_ERROR.message)
                            }
                        }
                    }

                    override fun onError(error: InteractionError) {
                        uiCallback.onError(error.msg)
                    }
                })
            }

            override fun onError(interactionError: InteractionError) {
                uiCallback.onError(interactionError.msg)
            }
        })
    }

    private fun createAndOpenLiveRoom(
        context: Context,
        param: OpenLiveParam,
        uiCallback: UICallback<String>
    ) {
        val currentUserId = Const.getUserId()
        val request = CreateLiveRequest()
        request.anchor = currentUserId
        request.title = param.title
        val jsonObject = JSONObject()
        try {
            jsonObject.put("userNick", UserManager.getUserName())
            jsonObject.put(
                "userAvatar",
                param.userAvatar
            )
            jsonObject.put(
                "cover_url",
                if (TextUtils.isEmpty(param.cover)) "" else  param.cover
            )
        } catch (e: JSONException) {
            e.printStackTrace()
        }
        request.extend = jsonObject.toString()
        request.anchor_nick = param.nick
        request.notice = param.notice
        request.mode = param.model
        AppServerApi.instance().createLive(request).invoke(object : InteractionCallback<LiveModel> {
            override fun onSuccess(liveModel: LiveModel) {
                val updateLiveRequest = UpdateLiveRequest()
                updateLiveRequest.id = liveModel.id
                updateLiveRequest.anchor = liveModel.anchorId
                updateLiveRequest.title = liveModel.title
                updateLiveRequest.notice = liveModel.notice
                AppServerApi.instance().updateLive(updateLiveRequest).invoke(null)
                openLiveRoom(context, liveModel, param, uiCallback)
            }

            override fun onError(error: InteractionError) {
                loge("创建直播间错误==="+error.code)
//                    uiCallback.onError(error.msg)
                RxBus.getDefault().post(
                    RxBusBean(
                        CustSignKey.LIVE_START_RUN,
                        CustSignKey.LIVE_START_RUN)
                )
                try {
                    var map= GsonUtil.jsonToMap(error.msg)
                    if (map!=null){
                        var str= map["message"].toString()
                        showToast(str)
                    }else{
                        uiCallback.onError(error.msg)
                    }
                }catch (e: Exception) {
                    uiCallback.onError(error.msg)
                }

            }
        })
    }

    //观众直接进入直播间
    private fun openLiveRoom(
        context: Context, createdLiveModel: LiveModel?, param: OpenLiveParam,
        uiCallback: UICallback<String>
    ) {
        if (createdLiveModel != null) {
            RxBus.getDefault().post(
                RxBusBean(
                    CustSignKey.LIVE_START_RUN,
                    CustSignKey.LIVE_START_RUN)
            )
            // 主播新建
            val liveParam = LiveParam()
            liveParam.liveId = createdLiveModel.id
            liveParam.liveModel = createdLiveModel
            liveParam.role =LiveRole.ANCHOR;
            liveParam.userNick = param.nick
            liveParam.userAvatar=param.userAvatar
            liveParam.userExtension = param.userExtension
            liveParam.notice = param.notice
            //跳转直播页面  LiveBroadcastActivity
            CustRouter.openBusinessRoomPage(context, liveParam)
            uiCallback.onSuccess(liveParam.liveId)
            return
        }
        val request = GetLiveRequest()
        request.id = param.liveId
        request.userId = Const.getUserId()
        AppServerApi.instance().getLive(request).invoke(object : InteractionCallback<LiveModel?> {
            override fun onError(error: InteractionError) {
                uiCallback.onError(error.msg)
            }
            override fun onSuccess(liveModel: LiveModel?) {
                if (liveModel!!.status==1){
                    RxBus.getDefault().post(
                        RxBusBean(
                            CustSignKey.LIVE_START_RUN,
                            CustSignKey.LIVE_START_RUN)
                    )
                    val liveParam = LiveParam()
                    liveParam.liveId = param.liveId
                    liveParam.liveModel = liveModel
                    liveParam.role = param.role
                    liveParam.userNick = param.nick
                    liveParam.userAvatar= param.userAvatar
                    liveParam.notice = liveModel.notice
                    liveParam.userExtension = param.userExtension
                    CustRouter.openBusinessRoomPage(context, liveParam)
                    uiCallback.onSuccess(liveParam.liveId)
                }else{
                    RxBus.getDefault().post(
                        RxBusBean(
                            CustSignKey.LIVE_START,
                            CustSignKey.LIVE_START)
                    )
                }
            }
        })
    }

    /**
//     * 打开直播间参数，role为必传参数
//     */
//    class OpenLiveParam {
//        var liveId: String? = null
//        var role: LivePrototype.Role? = null
//        var nick: String? = null
//        var userExtension: String? = null
//
//        // 公告
//        var notice: String? = null
//
//        // 标题
//        var title: String? = null
//
//        // 可选参数
//        var mediaPusherOptions: AliLiveMediaStreamOptions? = null
//
//        // 0:普通直播间; 1:连麦直播间;
//        var model = 0
//    }

    /**
//     * 角色
//     */
//     enum class Role(val value: String) {
//        /**
//         * 主播
//         */
//        ANCHOR("anchor"),
//
//        /**
//         * 观众
//         */
//        AUDIENCE("audience");
//
//        companion object {
//            fun ofValue(value: String): Role {
//                return if (ANCHOR.value == value) ANCHOR else AUDIENCE
//            }
//        }
//    }

    companion object {
        private val TAG = CustLiveProtoType::class.java.simpleName
        private val sInstanceLock = ByteArray(0)
        private var sInstance: CustLiveProtoType? = null
        val instance: CustLiveProtoType?
            get() {
                if (sInstance == null) {
                    synchronized(sInstanceLock) {
                        if (sInstance == null) {
                            sInstance = CustLiveProtoType()
                        }
                    }
                }
                return sInstance
            }
    }


    private fun fetchMessageToken(
        userInfo: AUIMessageUserInfo,
        interactionCallback: InteractionCallback<Void?>
    ) {
        val config = AUIMessageConfig()
        config.deviceId = CommonUtil.getDeviceId()
        AppServerTokenManager.fetchToken(userInfo.userId, object : InteractionCallback<String?> {
            override fun onSuccess(data: String?) {
                config.token = data
                MessageServiceFactory.getMessageService().setConfig(config)
                interactionCallback.onSuccess(null)
            }

            override fun onError(interactionError: InteractionError) {
                interactionCallback.onError(interactionError)
            }
        })
    }

    /**
     * 打开直播间参数，role为必传参数
     */
    class OpenLiveParam {
        var liveId: String? = null
        var role: LiveRole? = null
        var nick: String? = null
        var userAvatar: String? = null
        var userExtension: String? = null

        // 公告
        var notice: String? = null

        // 标题
        var title: String? = null

        // 可选参数
        var mediaPusherOptions: AliLiveMediaStreamOptions? = null

        // 0:普通直播间; 1:连麦直播间;
        var model = 1
        var cover: String? = null  //封面
    }
}